package com.mark.controller.common.interceptor;

import com.google.common.collect.Maps;
import com.mark.common.ServerResponse;
import com.mark.controller.common.SessionExpireFilter;
import com.mark.pojo.Admin;
import com.mark.util.CookieUtil;
import com.mark.util.JsonUtil;
import com.mark.util.PropertiesUtil;
import com.mark.util.RedisShardedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Choisaaaa on 2018/5/15.
 * 拦截器
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor{


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String methodName = handlerMethod.getMethod().getName();
        String className = handlerMethod.getBean().getClass().getSimpleName();
        StringBuffer requestParamBuffer = new StringBuffer();
        Map paramMap = request.getParameterMap();
        Iterator it = paramMap.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            String mapKey = (String) entry.getKey();
            String mapValue = StringUtils.EMPTY;
            Object object = entry.getValue();
            if(object instanceof String[]){
                String[] strs = (String[]) object;
                mapValue = Arrays.toString(strs);
            }
            requestParamBuffer.append(mapKey).append("=").append(mapValue);
        }
        if(StringUtils.equals(className,"AdminManageController") && StringUtils.equals(methodName,"login")){
            log.info("拦截器拦截到请求，className{}，methodName{}",className,methodName);
            return  true;
        }
        log.info("权限拦截器拦截到请求,className:{}, methodName:{}, param:{}",className,methodName,requestParamBuffer.toString());

        Admin currentAdmin = null;
        String adminLoginToken = CookieUtil.readAdminLoginToken(request);
        if(StringUtils.isNotEmpty(adminLoginToken)){
            String adminJsonStr = RedisShardedPoolUtil.get(adminLoginToken);
             currentAdmin = JsonUtil.string2Obj(adminJsonStr,Admin.class);
        }
        if(currentAdmin == null){
            String adminOrigin = PropertiesUtil.getProperty("admin.origin");
            response.reset();// 这里要添加reset，否则报异常 getWriter() has already been called for this response.
            SessionExpireFilter sessionExpireFilter = new SessionExpireFilter();
            sessionExpireFilter.addHeader(response,adminOrigin);//重置响应头信息 解决跨域问题
            PrintWriter out = response.getWriter();

            if(currentAdmin == null){
                if(StringUtils.equals(className,"ProductManageController") && StringUtils.equals(methodName,"richtextImgUpload")){
                    Map resultMap = Maps.newHashMap();
                    resultMap.put("success",false);
                    resultMap.put("msg","请登录管理员");
                    out.print(JsonUtil.obj2String(resultMap));
                }else{
                    out.print(JsonUtil.obj2String(ServerResponse.createByNeedLogin()));
                }
            }else{
                if(StringUtils.equals(className,"ProductManageController") && StringUtils.equals(methodName,"richtextImgUpload")){
                    Map<String,Object> resultMap = Maps.newHashMap();
                    resultMap.put("success",false);
                    resultMap.put("msg","无权限操作");
                    out.print(JsonUtil.obj2String(resultMap));
                }else{
                    out.print(JsonUtil.obj2String(ServerResponse.createByNeedLogin()));
                }
            }
            out.flush();
            out.close();// 这里要关闭
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
